package com.dai.dao;


import com.dai.bean.Task;
import com.dai.bean.TaskType;
import com.dai.bean.tasks.TaskHeShui;
import com.dai.bean.tasks.TaskZaoWan;
import org.springframework.stereotype.Component;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;

@Component("taskDAO")
public class TaskDAO extends BaseDAO<Task>{

    //  早晚打卡
    public TaskZaoWan getTaskZaoWan(int user_id){
        Task task = getTask(user_id);
        return getTaskZaoWan(task);
    }

    public TaskZaoWan getTaskZaoWan(Task task){
        if(task == null){
            return  null;
        }else{
            // 解析出需要的json数据
            JSONObject object = new JSONObject(task.userdata);
            JSONObject zwObj = object.getJSONObject(TaskType.ZaoWanDaKa.getValue());

            TaskZaoWan zw = new TaskZaoWan();
            zw.zaoExecuted = zwObj.getInt("zaoExecuted");
            zw.wanExecuted = zwObj.getInt("wanExecuted");
            return  zw;
        }
    }

    public TaskHeShui getTaskHeShui(int user_id){
        Task task = getTask(user_id);
        return  getTaskHeShui(task);
    }

    public TaskHeShui getTaskHeShui(Task task){
        if(task == null){
            return  null;
        }else{
            // 解析出需要的json数据
            JSONObject object = new JSONObject(task.userdata);
            JSONObject hsObj = object.getJSONObject(TaskType.HeShuiDaka.getValue());

            TaskHeShui hs = new TaskHeShui();
            hs.a1 = hsObj.getInt("a1");
            hs.a2 = hsObj.getInt("a2");
            hs.a3 = hsObj.getInt("a3");
            hs.a4 = hsObj.getInt("a4");
            hs.a5 = hsObj.getInt("a5");
            hs.a6 = hsObj.getInt("a6");
            hs.a7 = hsObj.getInt("a7");
            hs.a8 = hsObj.getInt("a8");
            return  hs;
        }
    }

    public Task getTask(int user_id){
        String sql = String.format("select * from task where user_id = %d;",user_id);
        return get(sql);
    }




    //-----------------------------------------------
    // 插入默认数据
    public void newTask(Task task){
        String sql = String.format("insert into task (user_id,userdata,refresh_daytime) values (%d,'%s','%s');",
                task.user_id,task.userdata,task.refresh_daytime);
        run(sql);
    }

    public void updateTask(Task task){
        String  sql = String.format("update task set userdata = '%s',refresh_daytime = '%s' where user_id = %d;",
                task.userdata,task.refresh_daytime,task.user_id);
        run(sql);
    }


}
